/* Player class */
function Player(id, name, pos, full_name)
{
	this.id = id;
	this.name = name;
	this.pos = pos;
	this.full_name = full_name;
}

/* Squad class */
function Squad(id)
{
	this.id = id;
	this.players = new Array();
	this.options = new Array();
	this.order = "pos";

	this.addPlayer = addPlayer;
	this.removePlayer = removePlayer;
	this.writeSquad = writeSquad;
	this.orderBy = orderBy;
}

function addPlayer(player)
{
	this.players.push(player);
}

function removePlayer(id)
{
	var player = null;
	for (var i = 0; i < this.players.length; ++i)
	{
		if (this.players[i].id == id)
		{
			player = this.players[i].id;
			this.players.splice(i, 1);
		}
	}

	return player;
}

function writeSquad()
{
	var select = document.getElementById(this.id);
	while (select.options.length)
		select.options[0] = null;

	for (var i = 0; i < this.players.length; ++i)
	{
		var text;
		if (this.order == "pos") text = this.players[i].name + ' - ' + this.players[i].pos;
		else if (this.order == "name") text = this.players[i].name + ' - ' + this.players[i].pos;
		else text = this.players[i].full_name + ' - ' + this.players[i].pos;

		select.options[i] = new Option(text, this.players[i].id);
	}
}

function orderBy(order)
{
	this.order = order;
	if (order == "pos")
		this.players.mergeSort(function (a, b) { return compare(position_to_order(a.pos), position_to_order(b.pos)); });
	else
		this.players.mergeSort(function (a, b) { return compare(a[order], b[order]); });

	this.writeSquad();
}

function compare(a, b)
{
	if (a > b) return 1;
	if (a < b) return -1;
	return 0;
}

function position_to_order(a)
{
	if (a == 'g') a = 0;
	else if (a == 'dr') a = 100;
	else if (a == 'dc') a = 200;
	else if (a == 'dl') a = 300;
	else if (a == 'dm') a = 400;
	else if (a == 'cm') a = 500;
	else if (a == 'am') a = 600;
	else if (a == 'fw') a = 700;
	else a = 10000;

	return a;
}

/* Team class */
function Team(id)
{
	this.id = id;
}

//  CUSTOM ARRAY OBJECT METHOD FOR SORTING NUMBERS AND STRINGS
Array.prototype.mergeSort = function(fn, start, end)
{
    // If this is the first call (not a recursion)
    if (arguments.length < 2) { start = 0; }
	if (arguments.length < 3) { end = this.length; }

    if( end-start > 1 )
    {
      var mid=parseInt( (start+end)/2 );
      this.mergeSort(fn,start,mid);
      this.mergeSort(fn,mid,end);

      var tmp=[];
      var start2=start;
      var mid2=mid;
      for(var i=0; i<end-start; ++i)
      {
        if      (start2 >= mid) { tmp[i] = this[mid2++] }
        else if (mid2 >= end) { tmp[i] = this[start2++] }
        else if (fn(this[start2], this[mid2]) <= 0)
                           { tmp[i] = this[start2++] }
        else               { tmp[i] = this[mid2++] }
      }
	  var class_name = [];
      for(i=0; i<end-start; ++i)
	  {
		  class_name[i] = this[i+start].className;
	  }
      for(i=0; i<end-start; ++i)
      {
        this[i+start] = tmp[i];
		this[i+start].className = class_name[i];
      }
    }
}


